package groep3.ssc.tmts;

import groep3.ssc.helpers.Encryption;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;


public class TMTSRunnable implements Runnable
{
    public static Object locker = new Object();
    private TMTSListener tmts_l;
    private ServerSocket serverSocket;

    public TMTSRunnable(TMTSListener tmts_l)
    {
        this.tmts_l = tmts_l;
        try
        {
            serverSocket = new ServerSocket(1400);
        } catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void run()
    {
        try
        {
            Socket clientSocket;
            while (serverSocket != null)
            {
                clientSocket = serverSocket.accept();
                System.out.println("Client accepted");
                new Thread(new clientHandler(clientSocket)).start();
            }
        } catch (IOException e)
        {
            e.printStackTrace();
        }

    }

    private class clientHandler implements Runnable
    {
        private static final String SERVER_CONNECTION_RESPONSE = "client accepted";
        private Socket client;

        public clientHandler(Socket clientSocket)
        {
            this.client = clientSocket;
        }

        @Override
        public void run()
        {
            try
            {
                InputStream in = client.getInputStream();
                BufferedReader buf = new BufferedReader(new InputStreamReader(in));
                String input;
                while (client.isConnected())
                {
                    input = buf.readLine();
                    if (input == null)
                        continue;
                    input = Encryption.decrypt(input);
                    System.out.println("INPUT " + input);
                    if (input.equals(SERVER_CONNECTION_RESPONSE))
                        TMTSFinder.searching = false;
                    else
                        tmts_l.givePulse(input);
                    break;

                }
            } catch (IOException e)
            {
                e.printStackTrace();
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }

    }
}
